package helper

import (
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"log"
	"google.golang.org/grpc/credentials"
)

func GetServerCredentials() credentials.TransportCredentials {
	cert, err := tls.LoadX509KeyPair("./cert/x509/server.crt", "./cert/x509/server.key")
	if err != nil {
		log.Fatalf("加载服务端证书失败, err: %v\n", err)
	}
	// 构建基于 TLS 的 TransportCredentials
	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("./cert/x509/ca.crt")
	if err != nil {
		log.Fatalf("读取公钥文件失败: %v\n", err)
	}

	if ok := certPool.AppendCertsFromPEM(ca); !ok {
		log.Fatal("failed to append certs")
	}
	creds := credentials.NewTLS(&tls.Config{
		// 设置证书链，允许包含一个或多个
		Certificates: []tls.Certificate{cert},
		// 要求必须校验客户端的证书 可以根据实际情况选用其他参数
		ClientAuth: tls.RequireAndVerifyClientCert, // NOTE: this is optional!
		// 设置根证书的集合，校验方式使用 ClientAuth 中设定的模式
		ClientCAs: certPool,
	})

	return creds
}

func GetClientCredentials() credentials.TransportCredentials {
	cert, err := tls.LoadX509KeyPair("./cert/x509/client.crt", "./cert/x509/client.key")
	if err != nil {
		log.Fatalf("加载客户端证书失败, err: %v\n", err)
	}

	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("./cert/x509/ca.crt")
	if err != nil {
		log.Fatalf("读取公钥文件失败: %v\n", err)
	}

	certPool.AppendCertsFromPEM(ca)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   "www.testgrpccert.com",
		RootCAs:      certPool,
	})
	return creds
}
